<?php

namespace app\user\middleware;

use service\exception\ServiceException;
use thans\jwt\exception\JWTException;
use thans\jwt\facade\JWTAuth;

class Jwt extends Base
{
// 中间件方法
    public function handle($request, \Closure $next)
    {
        // 验证jwt
        try {
            // 获取不做权限验证的控制器
            $noAuthController = config('api.no_auth_controller');

            $controller = strtolower($request->controller());
            if (in_array($controller, $noAuthController)) {
                return $next($request);
            }

            $token = JWTAuth::auth(); //token验证
            $user = [
                'id'    =>  $token['id']
            ];
            $request->user = $user;
            return $next($request);
        } catch (JWTException $e) {
            // 登录超时
            return $this->requestFailReturn("登录超时", ServiceException::EXCEPTION_LOGIN_OUT_TIME);
        } catch (\Exception $e) {
            return $this->requestFailReturn($e->getMessage(), $e->getCode());
        }
        // return $this->requestFailReturn("测试");
    }
}